<template>
  <div>
    <!-- 发送评论 -->
    <div v-clickoutside="hideReplyBtn" @click="inputFocus" class="my-reply">
      <el-avatar class="header-img" :size="40" :src="defaultImage"></el-avatar>
      <div class="reply-info">
        <div
            tabindex="0"
            contenteditable="true"
            id="replyInput"
            spellcheck="false"
            placeholder="输入评论..."
            class="reply-input"
            @focus="showReplyBtn"
            @input="onDivInput"
        ></div>
      </div>
      <div class="reply-btn-box" v-show="btnShow">
        <el-button class="reply-btn" size="default" @click="sendComment" type="primary">发表评论</el-button>
      </div>
    </div>

    <!-- 评论区 -->
    <div v-for="(item, i) in comments" :key="i" class="author-title reply-father">
      <el-avatar class="header-img" :size="40" :src="defaultImage"></el-avatar>
      <div class="author-info">
        <span class="author-name">{{ item.username }}</span>
        <span class="author-time">{{ item.create_time }}</span>
      </div>
      <div class="icon-btn">
        <!--
        <span @click="showReplyInput(i, item.username, item.id)">
          <i class="iconfont el-icon-s-comment"></i>评论 {{ item.commentNum }}
        </span>
        -->
        <span @click="toggleLike(item, i)">
          <i class="iconfont el-icon-caret-top"></i>点赞 {{ item.like }}
        </span>
      </div>
      <div class="talk-box">
        <p>
          <span class="reply">{{ item.text }}</span>
        </p>
      </div>

<!--      <div class="reply-box">
        <div v-for="(reply, j) in item.reply" :key="j" class="author-title">
          <el-avatar class="header-img" :size="40" :src="defaultImage"></el-avatar>
          <div class="author-info">
            <span class="author-username">{{ reply.from }}</span>
            <span class="author-time">{{ reply.time }}</span>
          </div>
          <div class="icon-btn">
            <span @click="showReplyInput(i, reply.from, reply.id)">
              <i class="iconfont el-icon-s-comment"></i>评论 {{ reply.commentNum }}
            </span>
            <i class="iconfont el-icon-caret-top"></i>点赞 {{ reply.like }}
          </div>
          <div class="talk-box">
            <p>
              <span>回复 {{ reply.to }}:</span>
              <span class="reply">{{ reply.comment }}</span>
            </p>
          </div>
        </div>
      </div>-->

      <!-- 回复评论 -->
      <div v-show="_inputShow(i)" class="my-reply my-comment-reply">
        <el-avatar class="header-img" :size="40" :src="myHeader"></el-avatar>
        <div class="reply-info">
          <div
              tabindex="0"
              contenteditable="true"
              spellcheck="false"
              placeholder="输入评论..."
              @input="onDivInput"
              class="reply-input reply-comment-input"
          ></div>
        </div>
        <div class="reply-btn-box">
          <el-button class="reply-btn" size="default" @click="sendCommentReply(i)" type="primary">发表评论</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref} from 'vue';
import {ElAvatar, ElButton, ElMessage} from 'element-plus';
import {addCommentService, getCommentsService} from "@/api/comments.js";
import {userInfoService} from "@/api/user.js";
import {addLikeService} from "@/api/comments.js";
import {cancelLikeService} from "@/api/comments.js";

const props = defineProps(['searchData'])
const defaultImage = ref("https://img.wjwj.top/2024/12/17/9a71ae57ef8edf75b75f8a0878c9a127.png");
const btnShow = ref(false);
const replyComment = ref('');
const myHeader = 'https://ae01.alicdn.com/kf/Hd60a3f7c06fd47ae85624badd32ce54dv.jpg';
const comments = ref([
  {
    user_id: 19870621,
    username: 'Lana Del Rey',
    avatar: 'https://ae01.alicdn.com/kf/Hd60a3f7c06fd47ae85624badd32ce54dv.jpg',
    text: '我发布一张新专辑Norman Fucking Rockwell,大家快来听啊',
    create_time: '2019年9月16日 18:43',
    commentNum: 2,
    like: 15,
    inputShow: false,
  },
  {
    username: 'Taylor Swift',
    id: 19891221,
    avatar: 'https://ae01.alicdn.com/kf/H94c78935ffa64e7e977544d19ecebf06L.jpg',
    text: '我发行了我的新专辑Lover',
    create_time: '2019年9月16日 18:43',
    commentNum: 1,
    like: 5,
    inputShow: false,
    reply: [],
  },
  {
    username: 'Norman Fucking Rockwell',
    user_id: 20190830,
    avatar: 'https://ae01.alicdn.com/kf/Hdd856ae4c81545d2b51fa0c209f7aa28Z.jpg',
    text: 'Plz buy Norman Fucking Rockwell on everywhere',
    create_time: '2019年9月16日 18:43',
    commentNum: 0,
    like: 5,
    inputShow: false,
    reply: [],
  },
]);
const queryParameters = ref({
  user_id:'',
  seedWord:'',
  compWord:''
})
const userInfo = ref({
  id:'',
  username:'',
  telephone:'',
  avatar:'',
  email:'',
  create_time:'',
  update_time:''
})

// 处理点击外部隐藏回复按钮
const hideReplyBtn = () => {
  btnShow.value = false;
  const replyInput = document.getElementById('replyInput');
  replyInput.style.padding = '10px';
  replyInput.style.border = 'none';
};

// 聚焦输入框
const inputFocus = () => {
  const replyInput = document.getElementById('replyInput');
  replyInput.style.padding = '8px 8px';
  replyInput.style.border = '2px solid blue';
  replyInput.focus();
};

// 显示回复按钮
const showReplyBtn = () => {
  btnShow.value = true;
};

/*// 显示回复输入框
const showReplyInput = (i, username, user_id) => {
  comments.value[index.value].inputShow = false;
  index.value = i;
  comments.value[i].inputShow = true;
  to.value = username;
  toId.value = id;
};*/

// 判断是否显示回复输入框
const _inputShow = (i) => {
  return comments.value[i].inputShow;
};

// 处理回复输入框内容
const onDivInput = (e) => {
  replyComment.value = e.target.innerHTML;
};

//获取评论
const getComments = async () =>{
  if(!queryParameters.value){
    ElMessage({
      showClose: true,
      type: 'warning',
      message: '搜素为空',
    });
    return;
  }
  try {
    const result1 = await userInfoService();
    userInfo.value = result1.data
    queryParameters.value.user_id = result1.data.id;
    queryParameters.value.seedWord = props.searchData.seedword;
    queryParameters.compWord = props.searchData.compWord;

    const result2 = (await getCommentsService(queryParameters.value)).data;
    comments.value = result2.data;
  }catch(error){
    ElMessage.error('获取评论信息失败')
    console.error(error)
  }
}
await getComments();

// 发送评论
const sendComment = async () => {
  if (!replyComment.value) {
    ElMessage({
      showClose: true,
      type: 'warning',
      message: '评论不能为空',
    });
    return;
  }
  try {
    const a = {};
    const timeNow = new Date().getTime();
    const time = dateStr(timeNow);
    const result = await userInfoService();

    a.user_id = result.data.user_id;
    a.username = result.data.username;
    a.text = replyComment.value;
    a.create_time = time;
    a.like = 0;
    a.seedword_id = queryParameters.value.seedword;
    a.compword = queryParameters.value.compword;
    a.fromHeadImg = defaultImage;
    a.commentNum = 0;
    a.score = 10;
    replyComment.value = '';
    document.getElementById('replyInput').innerHTML = '';
    await addCommentService(a);
    comments.value.push(a);

  }catch(error){
    ElMessage.error('上传评论失败');
    console.error(error);

  }
};

/*// 发送回复评论
const sendCommentReply = (i) => {
  if (!replyComment.value) {
    ElMessage({
      showClose: true,
      type: 'warning',
      message: '评论不能为空',
    });
    return;
  }
  const a = {};
  const timeNow = new Date().getTime();
  const time = dateStr(timeNow);
  a.from = myName;
  a.to = to.value;
  a.fromHeadImg = myHeader;
  a.comment = replyComment.value;
  a.time = time;
  a.commentNum = 0;
  a.like = 0;
  comments.value[i].reply.push(a);
  replyComment.value = '';
  document.getElementsByClassName('reply-comment-input')[i].innerHTML = '';
};*/

// 获取时间格式
const dateStr = (date) => {
  const time = parseInt((new Date().getTime() - date) / 1000);
  let s;
  if (time < 60 * 10) {
    return '刚刚';
  } else if (time < 60 * 60 && time >= 60 * 10) {
    s = Math.floor(time / 60);
    return s + '分钟前';
  } else if (time < 60 * 60 * 24 && time >= 60 * 60) {
    s = Math.floor(time / 60 / 60);
    return s + '小时前';
  } else if (time < 60 * 60 * 24 * 30 && time >= 60 * 60 * 24) {
    s = Math.floor(time / 60 / 60 / 24);
    return s + '天前';
  } else {
    const dateObj = new Date(parseInt(date));
    return `${dateObj.getFullYear()}/${dateObj.getMonth() + 1}/${dateObj.getDate()}`;
  }
};

// 切换点赞状态
const toggleLike = (comment, index) => {
  if (comment.likeState) {
    comment.like--; // 取消点赞
    comment.comment_id = comment.id;
    comment.user_id = userInfo.value.id;
    cancelLikeService(comment);
  } else {
    comment.like++; // 点赞
    comment.comment_id = comment.id;
    comment.user_id = userInfo.value.id;
    addLikeService(comment);
  }
  comment.likeState = !comment.likeState; // 更新点赞状态
};
</script>

<style lang="scss" scoped>
.my-reply {
  padding: 10px;
  background-color: #fafbfc;
  .header-img {
    display: inline-block;
    vertical-align: top;
  }

  .reply-info {
    display: inline-block;
    margin-left: 5px;
    width: 90%;
    @media screen and (max-width: 1200px) {
      width: 80%;
    }
    .reply-input {
      min-height: 20px;
      line-height: 22px;
      padding: 10px 10px;
      color: #ccc;
      background-color: #fff;
      border-radius: 5px;
      &:empty:before {
        content: attr(placeholder);
      }
      &:focus:before {
        content: none;
      }
      &:focus {
        padding: 8px 8px;
        border: 2px solid blue;
        box-shadow: none;
        outline: none;
      }
    }
  }

  .reply-btn-box {
    height: 25px;
    margin: 10px 0;
    .reply-btn {
      position: relative;
      float: right;
      margin-right: 15px;
    }
  }
}

.my-comment-reply {
  margin-left: 50px;
  .reply-input {
    width: flex;
  }
}

.author-title:not(:last-child) {
  border-bottom: 1px solid rgba(178, 186, 194, 0.3);
}

.author-title {
  padding: 10px;
  .header-img {
    display: inline-block;
    vertical-align: top;
  }
  .author-info {
    display: inline-block;
    margin-left: 5px;
    width: 60%;
    height: 40px;
    line-height: 20px;
    > span {
      display: block;
      cursor: pointer;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    .author-name {
      color: #000;
      font-size: 18px;
      font-weight: bold;
    }

    .author-time {
      font-size: 14px;
    }
  }

  .icon-btn {
    width: 30%;
    padding: 0 !important;
    float: right;
    @media screen and (max-width: 1200px) {
      width: 20%;
      padding: 7px;
    }
    > span {
      cursor: pointer;
    }
    .iconfont {
      margin: 0 5px;
    }
  }

  .talk-box {
    margin: 0 50px;
    > p {
      margin: 0;
    }
    .reply {
      font-size: 16px;
      color: #000;
    }
  }

  .reply-box {
    margin: 10px 0 0 50px;
    background-color: #efefef;
  }
}
</style>

